//
//  SearchViewController.m
//  product_B
//
//  Created by lanou on 16/6/6.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "SearchViewController.h"
#import "HomePageMainModel.h"
#import "SearchReadingModel.h"
#import "MusicModel.h"
#import "MovieMainModel.h"
#import "SearchAuthorModel.h"
#import "MusicTimeTableViewCell.h"
#import "HomePageNoteViewController.h"
#import "MusicListViewController.h"
#import "MovieDetailViewController.h"
#import "ReadTableViewController.h"
#import "UserViewController.h"
@interface SearchViewController () <UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UISearchBar *searchBar;
@property (nonatomic,strong)NSDictionary *dataDic;
@property (nonatomic,strong)NSString *searchString;
@property (nonatomic,strong)NSMutableArray *hpArray;
@property (nonatomic,strong)NSMutableArray *readingArray;
@property (nonatomic,strong)NSMutableArray *musicArray;
@property (nonatomic,strong)NSMutableArray *movieArray;
@property (nonatomic,strong)NSMutableArray *authorArray;
@property (nonatomic,strong)UITableView *tabelView;
@property (nonatomic,assign)NSInteger buttonIndex;
@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.hpArray = [NSMutableArray array];
    self.readingArray = [NSMutableArray array];
    self.musicArray = [NSMutableArray array];
    self.movieArray= [NSMutableArray array];
    self.authorArray = [NSMutableArray array];
    
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, kWidth, 50)];
    [self.searchBar setPlaceholder:@"输入搜索内容"];
    [self.searchBar setTranslucent:YES];
    [self.searchBar setBackgroundColor:[UIColor whiteColor]];
    [self.searchBar setTintColor:[UIColor grayColor]];
    [self.searchBar setShowsCancelButton:YES animated:YES];
    self.searchBar.delegate = self;
    
    NSArray *buttonArray = @[@"插图",@"阅读",@"音乐",@"影视",@"作者"];
    for (int i = 0; i < 5; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(kWidth/5*i, 75, kWidth/5, 30);
        [button setTitle:buttonArray[i] forState:UIControlStateNormal];
        [self.view addSubview:button];
        button.tintColor = [UIColor grayColor];
        button.tag = i+100;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    [self.view addSubview:_searchBar];
    
    self.tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 105, kWidth, kHeight-105) style:UITableViewStylePlain];
    self.tabelView.delegate = self;
    self.tabelView.dataSource = self;
    
    [self.view addSubview:_tabelView];
    [self.tabelView registerNib:[UINib nibWithNibName:@"MusicTimeTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.buttonIndex == 1) {
        return self.hpArray.count;
    }else if (self.buttonIndex == 2) {
        return self.readingArray.count;
    }else if (self.buttonIndex == 3) {
        return self.musicArray.count;
    }else if (self.buttonIndex == 4) {
        return self.movieArray.count;
    }else{
        return self.authorArray.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.buttonIndex == 1) {
        MusicTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        HomePageMainModel *model = self.hpArray[indexPath.row];
        [cell.picture sd_setImageWithURL:[NSURL URLWithString:model.hp_img_original_url]];
        cell.title.text = model.hp_title;
        cell.author.text = model.hp_author;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (self.buttonIndex == 2) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell1"];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        SearchReadingModel *model = self.readingArray[indexPath.row];
        cell.textLabel.text = model.title;
        return cell;
    }else if (self.buttonIndex == 3) {
        MusicTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        MusicModel *model = self.musicArray[indexPath.row];
        [cell.picture sd_setImageWithURL:[NSURL URLWithString:model.cover]];
        cell.title.text = model.title;
        cell.author.text = model.author.user_name;
        return cell;
    }else if (self.buttonIndex == 4) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell2"];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        MovieMainModel *model = self.movieArray[indexPath.row];
        cell.textLabel.text = model.title;
        return cell;
    }else{
        MusicTimeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        SearchAuthorModel *model = self.authorArray[indexPath.row];
        [cell.picture sd_setImageWithURL:[NSURL URLWithString:model.web_url]];
        cell.title.text = model.user_name;
        cell.author.text = model.desc;
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.buttonIndex == 1) {
        HomePageMainModel *model = self.hpArray[indexPath.row];
        HomePageNoteViewController *homePageNoteVC = [[HomePageNoteViewController alloc]init];
        homePageNoteVC.model = model;
        [self.navigationController pushViewController:homePageNoteVC animated:YES];
    }else if (self.buttonIndex == 2) {
        ReadTableViewController *tableVC = [[ReadTableViewController alloc]init];
        SearchReadingModel *model = self.readingArray[indexPath.row];
        tableVC.modelID = model.myId;
        if ([model.type isEqualToString:@"essay"]) {
            tableVC.indexY = 0;
        }else if ([model.type isEqualToString:@"question"]){
            tableVC.indexY = 2;
        }else{
            tableVC.indexY = 1;
        }
        tableVC.isAdd = YES;
        tableVC.isRihgt  = YES;
        [self.navigationController pushViewController:tableVC animated:YES];

    }else if (self.buttonIndex == 3) {
        MusicListViewController *musicVC = [[MusicListViewController alloc]init];
        musicVC.musicID = [self.musicArray[indexPath.row] myID];
        musicVC.isChild = YES;
        [self.navigationController pushViewController:musicVC animated:YES];
    
    }else if (self.buttonIndex == 4) {
        MovieDetailViewController *movieDetailVC = [[MovieDetailViewController alloc]init];
        MovieMainModel *model = self.movieArray[indexPath.row];
        movieDetailVC.movieMainModel = model;
        [self.navigationController pushViewController:movieDetailVC animated:YES];
    }else{
        UserViewController *userVC = [[UserViewController alloc]init];
        userVC.modelID = [self.authorArray[indexPath.row] user_id];
        [self.navigationController pushViewController:userVC animated:YES];
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{

    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    self.searchString = self.searchBar.text;
    self.searchString = [self.searchString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    for (UIButton *button in self.view.subviews) {
        button.hidden = NO;
    }
    [self.searchBar resignFirstResponder];
    
  
    [self.hpArray removeAllObjects];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/search/hp/%@",self.searchString] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = self.dataDic[@"data"];
        for (NSDictionary *dic in dataArray) {
            HomePageMainModel *model = [[HomePageMainModel alloc]init];
            [model  setValuesForKeysWithDictionary:dic];
            [self.hpArray addObject:model];
        }
        self.buttonIndex = 1;

        dispatch_async(dispatch_get_main_queue(), ^{
            [_tabelView reloadData];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
    
    [self.readingArray removeAllObjects];
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/search/reading/%@",self.searchString] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = self.dataDic[@"data"];
        for (NSDictionary *dic in dataArray) {
            SearchReadingModel *model = [[SearchReadingModel alloc]init];
            [model  setValuesForKeysWithDictionary:dic];
            [self.readingArray addObject:model];
        }
        self.buttonIndex = 2;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
    
    [self.musicArray removeAllObjects];
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/search/music/%@",self.searchString] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = self.dataDic[@"data"];
        for (NSDictionary *dic in dataArray) {
            MusicModel *model = [[MusicModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.musicArray addObject:model];
        }
        self.buttonIndex = 3;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
    
    [self.movieArray removeAllObjects];
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/search/movie/%@",self.searchString] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = self.dataDic[@"data"];
        for (NSDictionary *dic in dataArray) {
            MovieMainModel *model = [[MovieMainModel alloc]init];
            [model  setValuesForKeysWithDictionary:dic];
            [self.movieArray addObject:model];
        }
        self.buttonIndex = 4;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
    
    [self.authorArray removeAllObjects];
    [manager GET:[NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/search/author/%@",self.searchString] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.dataDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = self.dataDic[@"data"];
        for (NSDictionary *dic in dataArray) {
            SearchAuthorModel *model = [[SearchAuthorModel alloc]init];
            [model  setValuesForKeysWithDictionary:dic];
            [self.authorArray addObject:model];
        }
        self.buttonIndex = 5;

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
}

- (void)buttonAction:(UIButton *)sender{
    if (sender.tag == 100) {
   
        self.buttonIndex = 1;
    }
    if (sender.tag == 101) {
       
        self.buttonIndex = 2;
    }
    if (sender.tag == 102) {
        
        self.buttonIndex = 3;
    }
    if (sender.tag == 103) {
        
        self.buttonIndex = 4;
    }
    if (sender.tag == 104) {
        
        self.buttonIndex = 5;
    }
    [self.tabelView reloadData];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
